package com.Practice.estore.view;

import com.Practice.estore.model.Product;
import com. Practice.estore.service.ProductService;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    private Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);
    private final String CART_FILE = "shopping_cart.dat";

    public ConsoleShop() {
        loadShoppingCart(); // 启动时加载购物车
        System.out.println("购物车加载完成，当前有 " + shoppingCart.size() + " 种商品");
    }

    /**
     * 加载购物车数据
     */
    @SuppressWarnings("unchecked")
    private void loadShoppingCart() {
        File file = new File(CART_FILE);
        if (!file.exists()) {
            System.out.println("未找到历史购物车数据，将使用新购物车");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(CART_FILE))) {
            Map<String, Integer> savedCart = (Map<String, Integer>) ois.readObject();

            // 验证购物车中的商品是否仍然存在
            int validItems = 0;
            int removedItems = 0;

            for (String productId : new ArrayList<>(savedCart.keySet())) {
                if (productService.findProductById(productId) != null) {
                    validItems++;
                } else {
                    savedCart.remove(productId);
                    removedItems++;
                }
            }

            shoppingCart = savedCart;

            if (removedItems > 0) {
                System.out.println("注意：有 " + removedItems + " 种商品已下架，已从购物车中移除");
            }

            System.out.println("购物车数据加载完成，共 " + validItems + " 种有效商品");

        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载购物车失败，将使用空购物车: " + e.getMessage());
            shoppingCart = new HashMap<>();
        }
    }

    /**
     * 立即保存购物车数据（每次修改后调用）
     */
    private void saveShoppingCart() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(CART_FILE))) {
            oos.writeObject(shoppingCart);
            // 不在控制台输出保存信息，避免频繁提示
        } catch (IOException e) {
            System.out.println("保存购物车失败: " + e.getMessage());
        }
    }

    /**
     * 退出系统
     */
    private void exitSystem() {
        // 保存商品数据
        System.out.println("正在保存商品数据...");
        productService.saveData();

        // 购物车数据已经在每次修改时保存了，这里可以不再重复保存
        System.out.println("购物车数据已实时保存");

        System.out.println("感谢使用，再见！");
        scanner.close();
    }

    private void showMenu() {
        System.out.println("\n=== 欢迎来到商城 ===");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 自定义排序浏览商品");
        System.out.println("3. 添加商品到购物车");
        System.out.println("4. 从购物车移除商品");
        System.out.println("5. 查看购物车");
        System.out.println("6. 清空购物车");
        System.out.println("7. 退出");
        System.out.print("请输入您的选择: ");
    }

    private void showSortedProducts() {
        System.out.println("\n--- 排序方式选择 ---");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 按库存从少到多");
        System.out.println("5. 按名称升序");
        System.out.println("6. 按名称降序");
        System.out.print("请选择排序方式: ");

        int sortChoice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        Comparator<Product> comparator = null;
        switch (sortChoice) {
            case 1:
                comparator = Comparator.comparingDouble(Product::getPrice);
                System.out.println("按价格从低到高排序:");
                break;
            case 2:
                comparator = Comparator.comparingDouble(Product::getPrice).reversed();
                System.out.println("按价格从高到低排序:");
                break;
            case 3:
                comparator = Comparator.comparingInt(Product::getStock).reversed();
                System.out.println("按库存从多到少排序:");
                break;
            case 4:
                comparator = Comparator.comparingInt(Product::getStock);
                System.out.println("按库存从少到多排序:");
                break;
            case 5:
                comparator = Comparator.comparing(Product::getName);
                System.out.println("按名称升序排序:");
                break;
            case 6:
                comparator = Comparator.comparing(Product::getName).reversed();
                System.out.println("按名称降序排序:");
                break;
            default:
                System.out.println("无效的排序选择，将使用默认排序");
        }

        browseProducts(comparator);
    }

    private void browseProducts(Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        // 根据传入的比较器进行排序
        if (comparator != null) {
            products.sort(comparator);
        } else {
            // 使用自然排序（需Product实现Comparable接口）
            Collections.sort(products);
        }

        // 显示表头
        System.out.println("ID     | 商品名称               | 价格       | 库存");
        System.out.println("-------+-----------------------+------------+------");

        for (Product product : products) {
            System.out.printf("%-6s | %-20s | ¥%-9.2f | %d\n",
                    product.getId(), product.getName(), product.getPrice(), product.getStock());
        }
    }

    /**
     * 添加到购物车（修改后立即保存）
     */
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        int currentQuantity = shoppingCart.getOrDefault(productId, 0);
        shoppingCart.put(productId, currentQuantity + quantity);

        // 立即保存购物车
        saveShoppingCart();

        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！当前数量: " + shoppingCart.get(productId));
        System.out.println("购物车已自动保存");
    }

    /**
     * 从购物车移除商品（新增功能）
     */
    private void removeFromCart() {
        System.out.print("请输入要移除的商品ID: ");
        String productId = scanner.nextLine();

        if (!shoppingCart.containsKey(productId)) {
            System.out.println("错误：购物车中没有该商品！");
            return;
        }

        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("错误：商品不存在！");
            shoppingCart.remove(productId); // 清理无效商品
            saveShoppingCart();
            return;
        }

        System.out.print("请输入要移除的数量（当前数量: " + shoppingCart.get(productId) + "）: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：移除数量必须为正数！");
            return;
        }

        int currentQuantity = shoppingCart.get(productId);
        if (quantity >= currentQuantity) {
            // 移除全部
            shoppingCart.remove(productId);
            System.out.println("已将 '" + product.getName() + "' 从购物车中完全移除");
        } else {
            // 移除部分
            shoppingCart.put(productId, currentQuantity - quantity);
            System.out.println("已从购物车中移除 " + quantity + " 个 '" + product.getName() + "'，剩余数量: " + shoppingCart.get(productId));
        }

        // 立即保存购物车
        saveShoppingCart();
        System.out.println("购物车已更新并保存");
    }

    /**
     * 清空购物车（新增功能）
     */
    private void clearCart() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车已经是空的！");
            return;
        }

        System.out.print("确定要清空购物车吗？(y/N): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            shoppingCart.clear();
            saveShoppingCart(); // 立即保存空的购物车
            System.out.println("购物车已清空并保存");
        } else {
            System.out.println("取消清空操作");
        }
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int itemCount = 0;

        // 显示表头
        System.out.println("商品名称               | 单价       | 数量 | 小计");
        System.out.println("-----------------------+------------+------+----------");

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("%-20s | ¥%-9.2f | %-4d | ¥%-8.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                itemCount += quantity;
            } else {
                System.out.printf("商品ID: %s (该商品已下架)\n", productId);
            }
        }
        System.out.println("-----------------------+------------+------+----------");
        System.out.printf("商品种类: %d | 商品总数: %d | 总计: ¥%.2f\n",
                shoppingCart.size(), itemCount, total);
    }

    /**
     * 备份数据文件
     */
    private void backupData() {
        System.out.println("\n--- 数据备份功能 ---");
        System.out.println("正在备份数据文件...");
        if (productService.backupData()) {
            System.out.println("数据备份完成！");
        } else {
            System.out.println("数据备份失败！");
        }
    }

    public void start() {
        System.out.println("=== 电商系统启动 ===");
        System.out.println("数据文件: " + productService.getDataFilePath());
        System.out.println("购物车文件: " + CART_FILE);

        while (true) {
            showMenu();
            try {
                int choice = scanner.nextInt();
                scanner.nextLine(); // 消费掉换行符

                switch (choice) {
                    case 1:
                        browseProducts(null);
                        break;
                    case 2:
                        showSortedProducts();
                        break;
                    case 3:
                        addToCart();
                        break;
                    case 4:
                        removeFromCart();
                        break;
                    case 5:
                        viewCart();
                        break;
                    case 6:
                        clearCart();
                        break;
                    case 7:
                        exitSystem();
                        return;
                    case 99: // 隐藏管理员选项 - 数据备份
                        backupData();
                        break;
                    default:
                        System.out.println("无效的选项，请重新输入！");
                }
            } catch (Exception e) {
                System.out.println("输入错误，请输入数字选项！");
                scanner.nextLine(); // 清除错误的输入
            }
        }
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}